import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {TableUtil} from "../../../util/table-util";
import {ResponseUtil} from "../../../util/response-util";
import {PageSubject} from "../../../util/page-subject";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {MsgConstants} from "../../../constants/constants";
import {MsgResult} from "../../../models/msg-result";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {AlarmConfigService} from "./alarm-config.service";
import {MsgAPI} from "../msg-constants";
import {DataDictionaryService} from "../../../services/dataDictionary.service";

declare var $;

@Component({
  selector: 'app-alarm-config',
  templateUrl: './alarm-config.component.html',
  styleUrls: ['./alarm-config.component.css']
})
export class AlarmConfigComponent implements OnInit, AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;

  idArr: Array<string> = [];
  factors: Array<string>;
  table;
  isEdit: boolean = false;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private tableUtil: TableUtil,
              private responseUtil: ResponseUtil,
              private pageSubject: PageSubject,
              private dataDictionarysService: DataDictionaryService,
              private alarmConfigService: AlarmConfigService,
              private dialogService: OneDialogService) {
  }

  proxy = {
    "configAdd": () => this.addConfig(),
    "configCommit": () => this.saveConfig(),
    "configDelete": () => this.deleteConfig()
  };

  ngOnInit() {
    this.pushPage();
    this.initFacotrs();
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  private pushPage() {
    let path = new Path("报警管理", "");
    this.pageSubject.pushPage("报警设置", "报警设置", path);
  }

  /**
   * 获取所有的元模板类型
   */
  initFacotrs() {
    this.factors = [];
    this.dataDictionarysService.getChildDicByCode('MRBJYZ').subscribe(
      result => this.responseUtil.success(result, this.processResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *  获取所有类型
   * @param json
   */
  private processResult = (result: MsgResult) => {
    // console.log(result);
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      result.data.forEach(function (value) {
        this.factors.push(value.display);
        this.initConfigData();
      }, this)
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  /**
   * 刷新页面
   */
  reLoad() {
    this.initFacotrs();
    this.table.bootstrapTable('refresh');
  }

  /**
   * 保存操作
   * 1.点击保存时，获取数据；
   * 2.移除修改行，点击事件；
   * 3.绑定所有行，点击事件；
   * 4.提交编辑后的数据；
   */
  saveConfig() {
    //获取数据
    let params = this.getEditRowData();
    if (!params) {
      return;
    }
    // this.dealClickEventAfterGetDat();
    // 提交数据
    this.alarmConfigService.addOrUpateCofig(params).subscribe(
      result => this.responseUtil.success(result, this.getConfigAddFormData),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 对添加修改结果进行处理
   * @param result
   */
  private getConfigAddFormData = (result: MsgResult) => {
    if (MsgConstants.MSG_CODE_OK == result.code) {
      this.reLoad();
      this.isEdit = false;
    }
  }

  deleteConfig() {
    let ids = $.map(this.table.bootstrapTable('getSelections'), function (row) {
      return row.id;
    });
    this.table.bootstrapTable('remove', {
      field: 'id',
      values: ids
    });
    // console.log(this.table.bootstrapTable('getData'));
    this.saveConfig();
  }

  /**
   * 处理编辑行数据
   * @returns {string}
   */
  private getEditRowData() {
    let isPass = true, errMsg = "";
    let dataTr: Array<any> = [];
    this.table.find("tbody tr").each(function (i, n) {
      let dataTd: Array<string> = [];
      $(n).find("td").each(function (i, m) {
        dataTd.push(!$(m).find("input").val() ? "" : $(m).find("input").val().trim());
      });
      if (dataTd.length > 1) {
        if (!(/^(-?\d+)(\.\d+)?$/.test(dataTd[2]))) {
          isPass = false;
          errMsg = "预警值必须是正整数!";
          return;
        }

        if (!(/^(-?\d+)(\.\d+)?$/.test(dataTd[3]))) {
          isPass = false;
          errMsg = "报警值必须是正整数!";
          return;
        }

        if (!(/^(-?\d+)(\.\d+)?$/.test(dataTd[4]))) {
          isPass = false;
          errMsg = "超标值必须是正整数!";
          return;
        }
        let easy = Number.parseFloat(dataTd[2]);
        let alarm = Number.parseFloat(dataTd[3]);
        let ext = Number.parseFloat(dataTd[4]);

        if (easy > alarm) {
          isPass = false;
          errMsg = "预警值不能大于报警值";
          return;
        }
        if (alarm > ext) {
          isPass = false;
          errMsg = "报警值不能大于超标值";
          return;
        }

        dataTr.push(dataTd.join("_"));
      }
    });
    if (isPass) {
      return dataTr;
    }
    this.dialogService.modalInfo(errMsg);
    return;
  }

  addConfig() {

    if (!this.isEdit) {
      //添加行
      this.table.bootstrapTable('append', this.appendData());
      this.isEdit = true;
      return;
    } else {
      //提示保存
      this.dialogService.infoWithCancelBtn("有数据未保存，是否先保存？", () => this.saveConfig());
    }
  }

  appendData() {
    let append = [{
      id: '',
      factor: '',
      ruleName: '',
      easyAlarm: '',
      standardAlam: '',
      exceedAlarm: ''
    }];
    return append;
  }

  initConfigData() {
    this.table = this.tableUtil.load("one_table_config", {

      columns: [
        {width: '50', checkbox: true},
        {field: 'id', title: 'ID', visible: false, switchable: false},
        {field: 'factor', title: '监测因子', align: "left", halign: "left", formatter: this.formatterFactor},
        {field: 'easyAlarm', title: '预警值', align: "left", halign: "left", formatter: this.formatterTable},
        {field: 'standardAlam', title: '报警值', align: "left", halign: "left", formatter: this.formatterTable},
        {field: 'exceedAlarm', title: '超标值', align: "left", halign: "left", formatter: this.formatterTable}
      ],
      undefinedText: "",
      height: 711,
      toolbar: "#one_toolbar_config",
      url: MsgAPI.getRules,
      method: 'post',
      contentType: "application/x-www-form-urlencoded",
      //传递附加参数
      queryParams: (params) => {

        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        this.responseUtil.preSuccess(result);
        // result.data.forEach(function (value) {
        //   console.log(value);
        // });
        return {data: result.data};
      },
      onClickCell: (field, value, row, element) => {
        this.isEdit = true;
      }
    });
  }

  formatterTable = (value) => {
    // if (this.isEdit) {
    return `<div class="one-table-edit"><input type="text" value="${value}"></div>`
    // } else {
    //   return `<div class="one-table-edit">${value}</div>`
    // }
  };
  formatterFactor = (value) => {
    this.factors.forEach(function (val, index, array) {
      if (val == value) {
        this.factors.splice(index, 1);
      }
    }, this);

    return `<div class="one-table-edit"><input type="text" value="${value}" placeholder="请输入因子："></div>`;

  }
}
